package com.filldream.fastboot.common.util;

import com.alibaba.fastjson.JSON;
import com.filldream.fastboot.common.constant.FinalStr;
import lombok.extern.slf4j.Slf4j;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName DDErrorUtil
 * @Description 钉钉工具类
 * @Author RickSun
 * @Date 2020/1/18 15:04
 * @Version 1.0
 * https://ding-doc.dingtalk.com/doc#/serverapi2/qf2nxq
 */
@Slf4j
public class DDErrorUtil {

    public static void directSend(String exceptionMsg) {
        //钉钉地址
        String url = "https://oapi.dingtalk.com/robot/send?access_token=367c29d0411a2b9fb0e7a089972ef474f28aeb07d239aed7014057641d0b0fe8";

        //内容
        Map<String,Object> contentMap = new HashMap();
        contentMap.put("content","iFillDream:" + FinalStr.project_name + "\r\n" + exceptionMsg);

        //其他参数
        Map<String,Object> paramMap = new HashMap();
        paramMap.put("msgtype","text");
        paramMap.put("text",contentMap);
        sendPostByMap(url, paramMap);
        log.warn( "详细错误如下:\r\n ********错误内容******** \r\n" + exceptionMsg + "\r\n********错误结束********");
    }

    /**
     * 发送POST请求，参数是Map, contentType=x-www-form-urlencoded
     * @param url   钉钉Webhook地址
     * @param paramMap  报错参数
     * @return
     */
    public static String sendPostByMap(String url, Map<String, Object> paramMap) {
        Map<String, String> headParam = new HashMap();
        headParam.put("Content-type", "application/json;charset=UTF-8");
        return sendPost(url, paramMap, headParam);
    }


    /**
     * 发送POST请求
     * @param url 请求地址
     * @param paramMap 参数
     * @param headParam 头部参数
     * @return
     */
    public static String sendPost(String url, Map<String, Object> paramMap, Map<String, String> headParam) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性 请求头
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent","Fiddler");

            if (headParam != null) {
                for (Map.Entry<String, String> entry : headParam.entrySet()) {
                    conn.setRequestProperty(entry.getKey(), entry.getValue());
                }
            }
            //发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            //获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            //发送请求参数
            out.print(JSON.toJSONString(paramMap));
            //flush输出流的缓冲
            out.flush();
            //定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            log.info("钉钉机器人发送POST请求出现异常！" + e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }
}